#!/usr/bin/env python
# _*_ coding:utf8 _*_ 
__date__ = '2018/6/16 19:18'
__author__ = 'zhourudong'

import ast

from django import template
from assets.models import Host, Project

register = template.Library()


@register.filter(name='projects_list')
def projects_list(host):
    """ 通过主机对象 返回所有项目名列表 """
    host_obj = Host.objects.get(pk=host)
    data = host_obj.projects.all()

    host_projects_list = []
    for i in data:
        host_projects_list.append(i.project_name)

    return host_projects_list


@register.filter(name='business_service')
def host_services(name):
    """返回此主机上 正在运行的服务名列表 """

    s = []
    project_obj = Project.objects.get(service_name=name)
    host_obj_list = Host.objects.filter(projects=project_obj).order_by("id")

    for i in host_obj_list:
        # 所有服务
        t = i.service.all()
        for b in t:
            if b not in s:
                s.append(b)

    return s


@register.filter(name='group_str2')
def groups_str2(group_list):
    if len(group_list) < 3:
        return ' '.join([group.name for group in group_list])
    else:
        return '%s ...' % ' '.join([group.name for group in group_list[0:2]])


@register.filter(name='get_vm_info')
def get_vm_info(host_id):
    host = Host.objects.get(pk=host_id)
    vm = Host.objects.filter(vm=host)
    if vm:
        return vm
    else:
        return False


@register.filter(name='str_to_list')
def str_to_list(info):
    return ast.literal_eval(info)
